<template>
  <div>
    <form action="/">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="请输入要搜索的标签"
        @search="onSearch"
        @clear="onCancel"
        @update:model-value="onSearch"

      >
      <template #action>
        <van-button size="small" type="primary" @click="handleResult">搜索</van-button>
      </template>
    </van-search>
    </form>
    <van-divider>已选标签</van-divider>
    <van-row gutter="16" style="padding: 0 16px">
      <van-col v-for="tag in activeIds">
        <van-tag :show="true" closeable size="medium" type="primary" @close="handleClose(tag)">{{ tag }}</van-tag>
      </van-col>
    </van-row>
    <div v-if="activeIds.length === 0">暂无选中</div>
    <van-divider>选择标签</van-divider>
    <van-tree-select
      v-model:active-id="activeIds"
      v-model:main-active-index="activeIndex"
      :items="tagList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router';

defineExpose({
  name: 'search',
})

const searchValue = ref('')
const onCancel = () => {
  showToast('取消')
  tagList.value = originTagList
}
// 已选中的标签
const activeIds = ref<string[]>([])
const activeIndex = ref(0)
// 标签列表
const originTagList = [
  {
    text: '性别',
    children: [
      { text: '男', id: '男' },
      { text: '女', id: '女'},
    ],
  },
  {
    text: '年级',
    children: [
      { text: '大一', id: '大一' },
      { text: '大二', id: '大二' },
      { text: '大三', id: '大三' },
      { text: '大四', id: '大四' },
    ],
  },
  {
    text: '兴趣',
    children: [
      { text: '唱', id: '唱' },
      { text: '跳', id: '跳' },
      { text: 'rap', id: 'rap' },
      { text: '篮球', id: '篮球' },
    ],
  },
]
const tagList = ref(originTagList)
const handleClose = (tag: string) => {
  if (activeIds.value.length > 0) {
    const index = activeIds.value.indexOf(tag)
    if (index !== -1) {
      activeIds.value.splice(index, 1)
    }
  }
}
/**
 * 搜索过滤
 * @param val 输入框数据
 */
const onSearch = () => {
  const tempTagList = [...originTagList]
  tagList.value = tempTagList.map(parentTag => {
    const tempParentTag = {...parentTag}
    tempParentTag.children = tempParentTag.children.filter(item => item.text.includes(searchValue.value))
    return tempParentTag
  })
}
const router = useRouter()
/**
 * 搜索结果
 */
const handleResult = () => {
  if (activeIds.value.length === 0) {
    showToast('请选择标签')
    return
  }
  router.push({
    path: '/searchResult',
    query: {
      tags: activeIds.value,
    },
  })
}
</script>
